<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SearchController
 *
 * @author bui dinh luyen
 */
class SearchController extends CController {
    /**
     * @var string index dir as alias path from <b>application</b>,
     * default to <b>runtime.search</b>
     */
    private $_indexFiles = '../runtime/search';
    
    public function init(){
        Yii::import('application.vendors.*');
        require_once('Zend/Search/Lucene.php');
        parent::init();
    }
    
    public function actionCreate(){
        Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
        setlocale(LC_CTYPE, 'UTF-8');
        Zend_Search_Lucene_Analysis_Analyzer::setDefault(
            new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive ());
        $index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.'.$this->_indexFiles), true);
        $drugs = Drug::model()->findAll();
        foreach ($drugs as $drug){
            $doc = new Zend_Search_Lucene_Document();
            $doc->addField(Zend_Search_Lucene_Field::Text('name',
                    CHtml::encode($drug->name), 'utf-8'));
            $doc->addField(Zend_Search_Lucene_Field::Text('description',
                    CHtml::encode($drug->description), 'utf-8'));
            $index->addDocument($doc);
        }
        $index->commit();
        //echo 'Lucene index created';
    }
    
    public function actionSearch(){
        Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
        setlocale(LC_CTYPE, 'UTF-8');
        Zend_Search_Lucene_Analysis_Analyzer::setDefault(
            new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive ());
        if(($term = Yii::app()->getRequest()->getParam('q', null)) !== null){
            $index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.'.$this->_indexFiles));
            $results = $index->find($term);
            $query = Zend_Search_Lucene_Search_QueryParser::parse($term);
            $this->render('search', compact('results', 'term', 'query'));
        }
    }
}

?>
